<template>
	<view>
		<loading :showLoaded.sync="showLoaded"></loading>
		<navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
		<!-- 1行2列 -->
		<view class="goodsList">
			<view :style="{paddingBottom: (isIpx ? 75 : 55) + 'px' }">
				<view v-if="utoolsData && utoolsClassGoodsLists" style="min-height: calc( 100vh - 150rpx )">
					<!-- <view v-if="utoolsData && utoolsClassGoodsLists"  > -->
					<utools-parse id="utools-parse" page="category" @triggerComponent="onTriggerComponent"
						:utools-data="utoolsData" @onAddCart="onAddCart"></utools-parse>
				</view>
				<view v-if="hasMore > 0" class="has-more">没有更多了</view>
			</view>
		</view>
		<view class="ios_safe_zone" v-if="isIos">
			<view class="ios_safe_zone_line"></view>
		</view>
		<!-- 活动规则弹框 -->
		<view class="mask-box-2" v-if="isActivityRule" @click.stop="isActivityRule = false" @touchmove.stop.prevent
			catchtouchmove="true">
			<view class="params-padding-box-3" :style="{bottom: isIpx?'414rpx':'350rpx' }" @click.stop="stopClick">
				<image style="width: 654rpx; height: auto;" mode="widthFix" :src="ruleBoxData.title" alt="" />
				<scroll-view style="height: 280rpx;width: 100%;" scroll-y="true">
					<view
						style="display: flex;flex-direction:column; justify-content: flex-start;align-items: center;padding: 0;margin:0;font-size: 0;">
						<block v-for="(img, i) in ruleBoxData.list" :key="describe">
							<image style="width:100%;height:auto;" :src="img" mode="widthFix"></image>
						</block>
					</view>

				</scroll-view>
				<view @click.stop="isActivityRule = false"
					style="position:absolute;top:15rpx;right:14rpx; width: 90rpx;height: 90rpx"></view>
			</view>
		</view>
		<cart-toast v-if="showCartMsg" :cartMessage='cartMessage' :cartStatus="cartStatus" bottom="64rpx"></cart-toast>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
	</view>
</template>
<script module="filterChecked" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
	let observer = null;
	import api from '@/api/api';
	import tip from '@/utils/tip';
	import util from '@/utils/util.js'
	import NavBar from '@/components/common/navbar';
	import loading from '@/components/common/loading';
	import CartToast from '@/components/common/cartToast.vue';
	import {
		SYSTEM_INFO,
		MERCHANT_INFO,
		CUSTOMER_INFO,
		USER_INFO,
		CART_KEY
	} from '@/utils/constant';
	export default {
		components: {
			navBar: NavBar,
			loading: loading,
			CartToast: CartToast
		},
		data() {
			return {
				id: '',
				afterPage: '',
				currentPage: 1,
				pageSize: 50,
				pageTotal: 0,
				cmsImageSrc: '',
				preview: false,
				list: [],
				hasMore: 0,
				nowPages: '',
				isShowCustomNavBar: true,
				// 组件所需的参数
				navbarData: {
					showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
					navbarTitle: '', //导航栏 中间的标题
					isTopFixed: false,
					newLogo: uni.getStorageInfoSync('storeLogo'),
					hideHome: true
				},
				showLoaded: true,
				utoolsClassGoodsLists: null,
				utoolsData: null,
				navName: null,
				showCartMsg: false,
				cartMessage: '',
				cartStatus: false,
				basicsTag: null,
				isBasicsTag: true,
				isIos: false,
				isActivityRule: false,
				ruleBoxData: {
					title: 'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_01.png',
					list: [
						'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_02_01.png',
						'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_02_02.png',
						'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_02_03.png',
						'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_02_04.png',
					]
				},
				isPlp: true,
				shareImage:'',
				shareTitle: '',
				pagePath:'', //  当前页面路由
				pageQuery:'', //  当前页面url参数
				uttype: '',
			}
		},
		async onLoad(options = {}) {
			this.isIos = wx.getSystemInfoSync().system.includes('iOS') && wx.getSystemInfoSync()?.safeArea?.top > 20;
			const {
				id = 0, navName = null, utid = null,uttype='categoryPlp'
			} = options
			this.id = utid || id;
			this.navName = navName
			this.utid = utid || id
			this.uttype = uttype
			await this.$onLaunched;
			this.preview = getApp().globalData.cmsPreview ? getApp().globalData.cmsPreview : false;
			await this.init()
			this.getPageShareData({utid: this.id , uttype: uttype })
			// setTimeout(() => {
			// 	this.showLoaded = false
			// }, 800)
		},
		async onShow() {
			await this.$onLaunched;
			let that = this
			getApp().cl_tracker.track('mini_program_view', {
				path: 'pages/item/categoryList',
				pageName: '商城PLP',
			});
			that.$commonSensors.commonPageView('PLPView')
			setTimeout(() => {
				that.tabbarTimeout = true;
			}, 600)
		},
		onUnload(options) {
		  // 页面关闭后销毁实例
		  if (observer) {
		    observer.disconnect()
		  }
		},
		methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
			//	商品曝光埋点 监听
			handleListenShoplists(){
				const that = this;
				setTimeout(() => {
				  observer = uni.createIntersectionObserver(that, {
				    observeAll: true,
				    thresholds: [0.5]
				  });
				  observer.relativeToViewport({
				    bottom: 50
				  }).observe('#utools-parse >>> .shoplistItemMainimg', (res) => {
				    if (res.intersectionRatio > 0.5 && res.dataset.item && res.dataset.tracking) {
							let product_sku_list = [];
							let product_name_list = [];
							const items = res.dataset.item;
							const _trackData = JSON.parse(res.dataset.tracking);
							if (items.goods.skuCodes && items.goods.skuCodes[0]) product_sku_list.push(items.goods.skuCodes[0]);
							if (items.goods.itemName) product_name_list.push(items.goods.itemName);
							if (product_sku_list.length && product_name_list.length) {
								_trackData.data.product_sku_list = product_sku_list;
								_trackData.data.product_name_list = product_name_list;
								this.$commonSensors.lithaTrack.cTrack(_trackData.name, _trackData.data);
							}
				    }
				  })
				}, 1600)
			},
			clossLoading(){
				this.showLoaded = false;
				this.handleListenShoplists();
			},
			async init() {
				// 商品标签
				this.basicsTag = await this.getBasicsTag()
				let utoolsData = await this.getHomeUtoolsData()
				this.utoolsData = utoolsData
				if (this.utoolsData) {
					if (this.utoolsData.classId == 0) {
						this.utoolsClassGoodsLists = await this.getStoreGoods();
						// this.list =  this.utoolsClassGoodsLists
					} else {
						this.utoolsClassGoodsLists = await this.getCateGoods(this.utoolsData?.classId || 8066)
						// this.list = this.utoolsClassGoodsLists
					}
				}
			
				return null
			},
			async getPageShareData(option) {
						try {
							let shareCode = "";
							if (option) shareCode = option.utid ? option.uttype + option.utid : option.uttype;
							const res = await this.$commonFunction.getShareinfoByCode(shareCode);
							this.shareImage = res.shareImage;
							this.shareTitle = res.shareTitle;
							this.pagePath = res.pagePath; //  当前页面路由
							this.pageQuery = res.pageQuery; //  当前页面url参数
						} catch (e) {}
					},
			async getBasicsTag() {
				let tag = await api.getBasicsTag({
					key: 'item_status_label'
				});
				let arr = tag?.data?.value ? JSON.parse(tag?.data?.value) : []
				// arr.sort((a,b)=>  a?.status-b?.status )
				return arr
			},
			async getHomeUtoolsData() {

				let json;
				// if (this.utid) {
				// 	json = await api.getUtoolsJsonP({
				// 		utoolsId: this.utid,
				// 		type: 'categoryPlp'
				// 	});
				// } else {
					json = await api.getUtoolsJsonById({
						utoolsId: this.id
					});
				// }

				return json.success && json?.data ? JSON.parse(json.data) : null
			},

			// 获取门店商品
			getStoreGoods: async function() {
				return new Promise(async (resolve, reject) => {
					let that = this;
					let merchantInfo = uni.getStorageSync('merchantInfo')
					// 获取门店商品列表
					const json = await api.getStoreGoodsList({
						query: {
							merchantId: merchantInfo.cloudMerchantId,
							page: that.currentPage,
							size: that.pageSize,
						}
					});
					if (json.code === 1000) {
						this.storeProductList = json.data.content;
						// 判断是否显示已加载全部数据
						resolve(json.data.content)
					}
				})
			},
			setHasMore(n) {
				this.hasMore = n
			},
			/**
			 * 分类商品列表
			 */
			getCateGoods: async function(class_id, is_sort) {
				let that = this;
				let customerInfo = uni.getStorageSync('customerInfo');
				let memberDetails = uni.getStorageSync('memberDetails')
				let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
				let res = await this.$commonFunction.doSearchGoods(class_id, '', 1, 200, null, '', is_sort, '', '', '',
					'')
				let cateProductList = res.data.content; // 商品列表
				//sku实时库存查询
				let skuCodeList = [],
					goodsQ = [];
				for (let i = 0; i < cateProductList.length; i++) {
					skuCodeList = skuCodeList.concat(cateProductList[i].skuCodes)
				}
				if (skuCodeList.length) {
					skuCodeList = await this.setSkuCodeList(skuCodeList)
					for (let i = 0; i < skuCodeList.length; i++) {
						let reset = await this.getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList[i]);
						goodsQ = reset.length ? goodsQ.concat(reset) : goodsQ
					}
				}
				// 策略价格
				let list = [];
				cateProductList.forEach(async item => {
					item.frontQty = 0
					if (goodsQ && goodsQ.length) {
						for (let i = 0; i < goodsQ.length; i++) {
							if (item.skuCodes.indexOf(goodsQ[i].skuCode) !== -1 && goodsQ[i].availableQty >
								0) {
								item.frontQty += goodsQ[i].availableQty
							}
						}
					}
					if (!!item.strategies) {
						let res = await this.$commonFunction.priceRulesDeal(item.strategies, item
							.itemmCode)
						if (res.price !== 0) {
							if (item.itemCode == res.itemCode) {
								item.price = res.price
							}
						}
						if (res.rulesArr.length > 0) {
							if (item.itemCode == res.itemCode) {
								item.rulesArr = res.rulesArr
							}
						}
					}

					list.push(item)
				})
				return list
			},
			async setSkuCodeList(skuCodeList) {
				if (skuCodeList.length < 21) {
					return [skuCodeList]
				} else {
					const result = skuCodeList.flatMap((value, index, array) => {
						if (index % 20 === 0) {
							return [array.slice(index, index + 20)];
						}
						return [];
					});
					return result
				}
			},
			async getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList) {

				let reset = await api.getAvailableBatchQty({
					method: "POST",
					header: {
						'jwt': customerInfo.jwt,
						'content-type': 'application/json'
					},
					// query: JSON.stringify(skuCodeList)
					query: skuCodeList
				}, merchantInfo.cloudMerchantId);
				if (reset.msg == "SUCCESS" && reset?.data?.length) {
					return reset.data.filter(item => item.availableQty > 0)
				} else {
					return []
				}
			},


			enterProduct(item, index) {
				this.$commonSensors.PLPProductClick(item, index, this.navbarData.navbarTitle)
				let path = this.id == 0 ? '/pages/GTR/item?id=' + item.id : '/pages/item/item?id=' + item.itemId +
					'&valueId=' + item.valueId + '&hasExpose=true'
				uni.navigateTo({
					url: path
				})
			},

			onAddCart(e) {
				const {
					data
				} = e.detail
				this.goods = data
				this.addCart(e)
			},
			onTriggerComponent(e) {
				try {
					let {
						itemId,
						type = null,
						trackData = null,
						item = null
					} = e.detail.data;
					if (type == 'anchorsClick') {
						if (itemId == 'tip') {
								this.isActivityRule = true
						}
					}
					this.$commonUtoolsTrack.onTriggerComponent(e);
				} catch (e) {
					console.log("home-onTriggerComponent-error:", e)
				}
			},

			// 商品加入购物车功能
			async addCart(e) {
				try {
					const {
						data
					} = e.detail
					this.goodsId = data.itemId
					let that = this
					let merchantInfo = uni.getStorageSync('merchantInfo');
					let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
					let userInfo = uni.getStorageSync(USER_INFO);
					if (!customerInfo && !userInfo) {
						that.registerType = 'cart';
						that.getUserProfile();
						return false;
					} else if (!customerInfo && !!userInfo) {
						that.registerType = 'cart';
						that.$refs.registerWidgetRef.openJoinMemberModal()
						return false;
					}
					let goodsInfo = await this.getGoodsDetail(merchantInfo)
					if (!goodsInfo || goodsInfo.code != 1000) return this.handleCartToast({
						success: false,
						msg: "加入购物车失败"
					});
					// 加入购物车
					const cartRes = await this.$commonFunction.buildProductsAddCart({
						price: goodsInfo.data.skus[0].price,
						itemId: goodsInfo.data.itemId,
						valueId: goodsInfo.data.frontProperties[0].valueId,
						itemCode: goodsInfo.data.itemId,
						itemName: goodsInfo.data.itemName,
						qty: 1,
						skuCode: goodsInfo.data.skus[0].skuCode,
						skuId: goodsInfo.data.skus[0].skuId,
					});
					//  加入购物车提示
					this.handleCartToast(cartRes);
				} catch (e) {
					this.handleCartToast({
						success: false,
						msg: "加入购物车失败"
					});
				}
			},
			/**
			 * 加购提示
			 * @param {Object} obj
			 */
			async handleCartToast(obj) {
				const _arr = ['您动作太快，请慢点哟～', '网络状态不佳，请重试'];
				if(obj.msg && _arr.includes(obj.msg)){
					this.handleShowTextToast(obj.msg)
				}else if(obj.data && obj.data.msg && obj.data.type === 'showToast'){
					this.handleShowTextToast(obj.data.msg)
				}else{
					if (obj?.success) this.getCartList();
					this.cartMessage = obj?.msg || "加入购物车失败";
					this.cartStatus = obj?.success || false;
					this.showCartMsg = true;
					setTimeout(() => {
						this.showCartMsg = false;
					}, 3000);
				}
			},
			//获取商品详情
			async getGoodsDetail(merchantInfo) {
				const json = await api.goodsDetail({
						query: {
							merchant_id: merchantInfo.cloudMerchantId,
							store_id: merchantInfo.cloudMerchantStoreId
						}
					},
					this.goodsId
				);
				return json
			},
			getUserProfile: async function() {
				let that = this
				this.$commonFunction.commonLoginNew().then(res => {
					if (res.code !== 1000) {
						this.$refs.registerWidgetRef.openJoinMemberModal()
					}else if(res.data && res.data.mobile){
            //  非大陆手机号按照非会员对待,重新入会
            const phoneNumberReg = /^1\d{10}$/;
            if(!phoneNumberReg.test(res.data.mobile)){
              this.$refs.registerWidgetRef.openJoinMemberModal()
            }
          }
				}).catch(err => {
					this.$refs.registerWidgetRef.openJoinMemberModal()
				})
			},
			/** 21岁弹窗确认 */
			onRegisterWidgetFinish(e) {
				return null
			},
			async registerSuccess() {
				let that = this
				that.showRegister = 1
				return null
				// that.$refs.cmsPage.toParseRegisterSuccess()
			},

			//获取购物车商品列表
			getCartList: async function() {
				let that = this;
				let cart_key = uni.getStorageSync(CART_KEY);
				let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
				try {
					if (jwt && cart_key !== null) {
						that.$commonFunction.getCartList().then((res) => {
							if (res && res.items !== null) {
								getApp().globalData.cartNum = res.availableTotalQty;
								that.cartNum = res.availableTotalQty;
								that.$store.commit('changeCartNum', res.availableTotalQty);
								uni.setStorageSync('cartNum', res.availableTotalQty);
							}
						}).catch((err) => {
							// tip.plainText(err.msg);
						});
					}
				} catch (err) {
					console.log(err)
				}
			},
			onShareAppMessage: async function(res) {
				let that = this
				if (res.from === 'button') {} else {
					this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
				}
				let imageUrl = this.shareImage || this.shareImageUrl
				let path = '/pages/item/categoryList?id=' + this.id + '&navName=' + this.navName +'&uttype='+ this.uttype
				let title = this.shareTitle || uni.getStorageSync('storeName') || 'THE MACALLAN EBOUTIQUE麦卡伦'
				this.$commonSensors.sensorsPageShare();
				this.$sr.setContext({ share_title: title });
				return this.$commonFunction.commonShare(res, title, path, imageUrl)
			},
			async getTsBySku(productSKU, tsId = null) {
				let customerInfo = wx.getStorageSync('customerInfo');
				let merchantInfo = wx.getStorageSync('merchantInfo');
				let memberDetails = wx.getStorageSync('memberDetails');
				let query = {
					"store_id": merchantInfo.cloudMerchantStoreId,
					"sku_id": productSKU,
					"group_id": customerInfo.groupId,
					"member_level_id": memberDetails.memberLevelId,
					"merchant_id": merchantInfo.cloudMerchantId,
					'campaign_target_sale_id': tsId || ''
				}
				const result = await api.getTsBySku({
					header: {
						jwt: customerInfo.jwt
					},
					method: 'GET',
					query: query,
				});
				if (result.code == 1000) {
					let {
						campaignEndTime,
						campaignStartTime,
						status
					} = result.data
					let now = new Date().getTime()
					let startTime, endTime; // 开始
					let systemInfo = wx.getSystemInfoSync()
					let isIos = systemInfo.system.indexOf("iOS");
					if (isIos == 0) {
						startTime = campaignStartTime && new Date(campaignStartTime.replace(/-/g, "/")).getTime();
						endTime = campaignEndTime && new Date(campaignEndTime.replace(/-/g, "/")).getTime();
					} else {
						startTime = campaignStartTime && new Date(campaignStartTime).getTime();
						endTime = campaignEndTime && new Date(campaignEndTime).getTime();
					}
					return   startTime <= now &&now < endTime
				} else {
					return false
				}

			},
			
			// onShareTimeline() {
			//   return {
			//     title: this.shareTitle ? this.shareTitle : uni.getStorageSync('storeName') || 'THE MACALLAN EBOUTIQUE麦卡伦',
			//     query: this.pageQuery,
			//     imageUrl: this.shareImage
			//   };
			// },
			// 商品详情信息
			async getGoodsDetailNew(goodsId) {
				// return null
				let that = this;
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
				let merchantInfo = uni.getStorageSync('merchantInfo') || (await getApp().getMerchantInfo());
				const json = await api.goodsDetail({
						query: {
							merchant_id: merchantInfo.cloudMerchantId,
							store_id: merchantInfo.cloudMerchantStoreId
						}
					},
					goodsId
				);
				let data = null
				if (json.code === 1000) {
					data = json.data;
				}
				return data
			}
		}
	}
</script>

<style lang="less">
	page {
		// background-color: #fff;
	}

	/* banner */
	.bannerBox {
		margin: 15rpx 15rpx 0;
		background-color: #f9f9f9;
	}

	/* 列表 */
	.goodsList {

		margin-top: 15rpx;
		position: relative;
	}

	.has-more {
		font-size: 12px;
		color: #C6C6C6;
		background: #fff;
		width: 100%;
		height: 104rpx;
		text-align: center;
		line-height: 104rpx;
	}

	.ell {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.trans {
		opacity: 0;
	}
	.mask-box-2 {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 99;
		background-color: rgba(0, 0, 0, 0.8);
	}

	.params-padding-box-3 {
		overflow: hidden;
		background: #FFFFFF;
		position: absolute;
		left: 48rpx;
		width: 654rpx;
		height: 796rpx;

	}


</style>
